import axios, { AxiosRequestConfig } from 'axios'
import { npsStart, npsDone } from '@/utils/nprogress'
import 'nprogress/nprogress.css'
import useUserStore from '@/store/modules/user'
import { resultInt } from '@/types/common'

const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 2000
  // headers: {'X-Custom-Header': 'foobar'}
})
// 请求拦截
instance.interceptors.request.use(
  (config) => {
    npsStart()
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.token = userStore.token
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
instance.interceptors.response.use(
  (response) => {
    npsDone()
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 *封装请求函数
 * @param options axios请求参数
 * @returns resultInt<T> T可由调用方传入数据类型
 */
export const request = <T>(options: AxiosRequestConfig) => {
  return new Promise<resultInt<T>>((resolve, reject) => {
    instance({
      ...options
    })
      .then((res) => {
        console.log('封装函数的res', res)
        if (res.status >= 200 && res.status < 300) {
          // 状态码2xx,表示http请求成功
          const code = res.data?.code
          console.log('123123123', code)

          if (code === 200) {
            resolve(res.data as resultInt<T>)
          } else {
            ElMessage({
              message: (res.data as resultInt<T>)?.msg || '请求错误',
              type: 'error'
            })
            reject(res)
          }
        } else if (res.status === 401) {
          // 401表示权限不足, 清理信息, 跳转登录

          reject(res)
        } else {
          ElMessage({
            message: (res.data as resultInt<T>)?.msg || '请求错误',
            type: 'error'
          })
          reject(res)
        }
      })
      .catch((error) => {
        console.log('网络错误', error)
        ElMessage({
          message: '网络错误,换个网络试试',
          type: 'error'
        })
        reject(error)
      })
  })
}
